package com.ali.juejin.utils

import com.ali.juejin.bean.CommonResponseEmptyBean
import com.ali.juejin.bean.v1.RecommendBean
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.internal.http.promisesBody
import okio.Buffer
import okio.EOFException
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.nio.charset.UnsupportedCharsetException


class Request constructor(val tempBaseUrl:String) {

    private val baseUrl = if(tempBaseUrl.isNotEmpty()) tempBaseUrl else "https://"

    private val sp = SPUtils.getInstance()

    private val okhttp = OkHttpClient.Builder().connectTimeout(10,
        java.util.concurrent.TimeUnit.SECONDS
    ).addInterceptor {
        val request = it.request()
//        LogUtils.wTag("url",request.url.queryParameterNames)
        val builder = request.newBuilder()
        val httpUrl = request.url.newBuilder()
        httpUrl.addEncodedQueryParameter("device_id",sp.getString("device_id"))
            .addEncodedQueryParameter("client_id",sp.getString("device_id"))
            .addEncodedQueryParameter("src","android")
            .addEncodedQueryParameter("token",sp.getString("token"))

        builder.addHeader("X-Juejin-Src","android")
            .addHeader("X-Legacy-Token",sp.getString("token"))
            .addHeader("X-Juejin-Client",sp.getString("device_id"))
            .addHeader("X-Legacy-Device-Id",sp.getString("device_id"))
            .addHeader("X-Juejin-Suid","jNeVvEY7mRjmRjErRuqy")
            .addHeader("X-Agent","OPPO/OPPO R17 Android/5.1.1 Juejin/Android/5.9.3")
            .url(httpUrl.build())

            it.proceed(builder.build())
        }
//    .addInterceptor {
//        val request = it.request()
//        val response = it.proceed(request)
//        val responseBody = response.body
//        val contentLength = responseBody?.contentLength()
//        if(!response.promisesBody()){
//
//        }else if(bodyEncoded(response.headers)){
//
//        }else{
//            val source = responseBody?.source()
//            source?.request(Long.MAX_VALUE)
//            val buffer = source?.buffer
//            var charset = Charsets.UTF_8
//            val contentType = responseBody?.contentType()
//            contentType?.let {
//                try {
//                    charset = contentType.charset(Charsets.UTF_8)!!
//                }catch (e:UnsupportedCharsetException){
//                    response
//                }
//            }
//            if(!isPlaintext(buffer!!)){
//                return@addInterceptor response
//            }
//            if(contentLength != 0L){
//                // 响应结构变动时临时结构读出
//                val result = buffer.clone().readString(charset)
//                val json:RecommendBean = Gson().fromJson(result,object :TypeToken<RecommendBean>(){}.type)
////                LogUtils.wTag("返回内容",json)
//                if(json.err_no != 0){
//                    ToastUtils.showShort(json.err_msg)
//                }
//            }
//        }
//        response
//    }
    .build()


    private val retrofit by lazy { Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create()).client(okhttp).build() }

    companion object{
        fun instance(tempBaseUrl:String=""):Retrofit{
            return Request(tempBaseUrl).retrofit
        }
    }

    @Throws(EOFException::class)
    private fun isPlaintext(buffer: Buffer):Boolean{
        return try {
            val prefix = Buffer()
            val byteCount = if (buffer.size < 64) buffer.size else 64.toLong()
            buffer.copyTo(prefix, 0, byteCount)
            for (i in 0..15) {
                if (prefix.exhausted()) {
                    break
                }
                val codePoint = prefix.readUtf8CodePoint()
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(
                        codePoint
                    )
                ) {
                    return false
                }
            }
            true
        } catch (e: EOFException) {
            false // Truncated UTF-8 sequence.
        }
    }
    private fun bodyEncoded(headers: Headers): Boolean {
        val contentEncoding: String? = headers.get("Content-Encoding")
        return contentEncoding != null && !contentEncoding.equals("identity", ignoreCase = true)
    }

}